package cn.net.isir.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuxubo
 * @filename HttpUtils.java
 * @package cn.net.isir.common
 * @email lxb@isir.net.cn
 * @date 2018/09/21
 * @comment
 * @since 1.7
 */
public class HttpUtils {
    // 声明log4j日志
    private static Logger logger = Logger.getLogger(HttpUtils.class);


    /**
     * 发送HTTP请求，请求内容是XML,编码是UTF-8
     *
     * @param urlStr  请求地址
     * @param xmlInfo XML内容
     * @return 结果
     */
    public static String sendXMLByPOST(String urlStr, String xmlInfo, String characterSet) {

        StringBuilder sb = new StringBuilder();
        if (characterSet == null) {
            characterSet = "utf-8";
        }
        try {

            urlStr = urlStr.replaceAll("&", "%26");
            urlStr = urlStr.replaceAll(" ", "%20");

            URL url = new URL(urlStr);
            URLConnection con = url.openConnection();
            con.setDoOutput(true);
//            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");

//            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), characterSet);
            OutputStream out = con.getOutputStream();
            logger.info("urlStr=" + urlStr);
//            out.write(new String(xmlInfo.getBytes(characterSet)));
            out.write(xmlInfo.getBytes(characterSet));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), characterSet));
            String line;
            for (line = br.readLine(); line != null; line = br.readLine()) {
                logger.info(line);
                sb.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 发送 post请求访问本地应用并根据传递参数不同返回不同结果
     */
    public static String post(String url, Map<String, Object> paramMap) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
//        formparams.add(new BasicNameValuePair("type", "house"));
        for (String key : paramMap.keySet()) {
            formparams.add(new BasicNameValuePair(key, String.valueOf(paramMap.get(key))));
        }
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            logger.info(uefEntity);
            httppost.setEntity(uefEntity);
            logger.info("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                String resp = null;
                if (entity != null) {
                    resp = EntityUtils.toString(entity, "UTF-8");
                    logger.info("--------------------------------------");
                    logger.info("Response content: " + resp);
                    logger.info("--------------------------------------");
                    return resp;
                }
                return null;
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 发送json数据
     *
     * @param url  请求地址
     * @param json 数据
     * @return 请求结果
     */
    public static String postJSON(String url, JSONObject json) {
        String result;
        try {
//            HttpClient client = new DefaultHttpClient();//已过时
            HttpClient client = HttpClientBuilder.create().build();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "application/json");
//            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            in.close();
            result = sb.toString();
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            logger.info("请求异常");
            throw new RuntimeException(e);
        }
        logger.info("result==" + result);
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求(腾讯小程序发送消息模板专用)
     *
     * @param url  发送请求的 URL
     * @param json 请求参数，请求参数应该是 json 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String jsonPost(String url, JSONObject json) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
            //上一行改为此,防止模板消息中的中文乱码
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
            out = new PrintWriter(outWriter);
            // 发送请求参数

            out.print(json);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

}
